package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Cate;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.Type;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.DeptApply;
import com.ruoyi.system.service.IDeptApplyService;

import javax.annotation.Resource;

/**
 * 部门Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-30
 */
@Service
public class DeptApplyServiceImpl implements IDeptApplyService {
    @Resource
    private DeptApplyMapper deptApplyMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private CateMapper cateMapper;
    @Autowired
    private CateServiceImpl cateServiceImpl;

    /**
     * 查询部门
     *
     * @param id 部门主键
     * @return 部门
     */
    @Override
    public DeptApply selectDeptApplyById(Long id) {
        return deptApplyMapper.selectDeptApplyById(id);
    }

    /**
     * 查询部门列表
     *
     * @param deptApply 部门
     * @return 部门
     */
    @Override
    public List<DeptApply> selectDeptApplyList(DeptApply deptApply) {
        List<DeptApply> deptApplies = deptApplyMapper.selectDeptApplyList(deptApply);
        Map<Long, Cate> cateMap = cateMapper.selectCateList(new Cate()).stream().collect(Collectors.toMap(Cate::getId, t -> t));
        deptApplies.forEach(item -> {
            if (item.getCate() != null && !"".equals(item.getCate())) {
                StringBuilder cateStr = new StringBuilder();
                for (String cate : item.getCate().split(",")) {
                    if (cateMap.containsKey(Long.valueOf(cate))) {
                        cateStr.append(cateMap.get(Long.valueOf(cate)).getName()).append(",");
                    }

                }
                if (cateStr.length() > 0) {
                    item.setCateStr(cateStr.substring(0, cateStr.lastIndexOf(",")));
                }
            }
        });
        return deptApplies;
    }

    /**
     * 新增部门
     *
     * @param deptApply 部门
     * @return 结果
     */
    @Override
    public int insertDeptApply(DeptApply deptApply) {
        deptApply.setCreateTime(DateUtils.getNowDate());

        if (deptApply.getPhone() == null || "".equals(deptApply.getPhone())) {
            throw new ServiceException("未填写手机号");
        }

        List<DeptApply> deptApplies = deptApplyMapper.selectDeptApplyList(new DeptApply() {{
            setPhone(deptApply.getPhone());
        }});
        if (deptApplies != null && !deptApplies.isEmpty()) {
            throw new ServiceException("手机号已存在");
        }

        List<SysUser> sysUserList = sysUserMapper.selectUserList(new SysUser() {{
            setUserName(deptApply.getPhone());
        }});
        if (sysUserList != null && !sysUserList.isEmpty()) {
            throw new ServiceException("手机号已存在");
        }

        return deptApplyMapper.insertDeptApply(deptApply);
    }

    /**
     * 修改部门
     *
     * @param deptApply 部门
     * @return 结果
     */
    @Override
    public int updateDeptApply(DeptApply deptApply) {
        deptApply.setUpdateTime(DateUtils.getNowDate());

        if (deptApply.getPhone() == null || "".equals(deptApply.getPhone())) {
            throw new ServiceException("未填写手机号");
        }

        List<DeptApply> deptApplies = deptApplyMapper.selectDeptApplyList(new DeptApply() {{
            setPhone(deptApply.getPhone());
        }});
        if (deptApplies != null && !deptApplies.isEmpty()) {
            if (!deptApplies.get(0).getId().equals(deptApply.getId())) {
                throw new ServiceException("手机号已存在");
            }
        }

        List<SysUser> sysUserList = sysUserMapper.selectUserList(new SysUser() {{
            setUserName(deptApply.getPhone());
        }});
        if (sysUserList != null && !sysUserList.isEmpty()) {
            throw new ServiceException("手机号已存在");
        }

        DeptApply deptApply_old = deptApplyMapper.selectDeptApplyById(deptApply.getId());

        int i = deptApplyMapper.updateDeptApply(deptApply);

        //审核通过
        if (Integer.parseInt(deptApply_old.getStatus()) == 0 && Integer.parseInt(deptApply.getStatus()) == 1) {
            SysDept sysDept = new SysDept();
            sysDept.setParentId(deptApply_old.getParentId());
            sysDept.setAncestors(deptApply_old.getAncestors());
            sysDept.setDeptName(deptApply_old.getDeptName());
            sysDept.setLeader(deptApply_old.getLeader());
            sysDept.setPhone(deptApply_old.getPhone());
            sysDept.setEmail(deptApply_old.getEmail());
            sysDept.setLicense(deptApply_old.getLicense());
            sysDept.setCode(deptApply_old.getCode());
            sysDept.setIdCardTop(deptApply_old.getIdCardTop());
            sysDept.setIdCardBack(deptApply_old.getIdCardBack());
            sysDept.setFoodInspector(deptApply_old.getFoodInspector());
            sysDept.setHealth(deptApply_old.getHealth());
            sysDept.setPerformance(deptApply_old.getPerformance());
            sysDept.setCate(deptApply_old.getCate());
            sysDept.setNature(deptApply_old.getNature());
            sysDept.setAptitude(deptApply_old.getAptitude());
            sysDept.setAddress(deptApply_old.getAddress());
            sysDept.setArea(deptApply_old.getArea());
            sysDept.setEquity(deptApply_old.getEquity());
            sysDept.setEquityCert(deptApply_old.getEquityCert());
            sysDept.setIso9001(deptApply_old.getIso9001());
            sysDept.setIso14001(deptApply_old.getIso14001());
            sysDept.setHaccp(deptApply_old.getHaccp());
            sysDept.setCnas(deptApply_old.getCnas());
            sysDept.setCar(deptApply_old.getCar());
            sysDept.setCarNum1(deptApply_old.getCarNum1());
            sysDept.setCarNum2(deptApply_old.getCarNum2());
            sysDept.setIsCar(deptApply_old.getIsCar());
            sysDept.setFoodInsurance(deptApply_old.getFoodInsurance());
            sysDept.setSumInsured(deptApply_old.getSumInsured());
            sysDept.setSocialSecurity(deptApply_old.getSocialSecurity());
            sysDept.setOther(deptApply_old.getOther());
            sysDept.setType(deptApply_old.getType());
            sysDeptMapper.insertDept(sysDept);

            //新增部门用户
            SysUser sysUser = new SysUser();
            sysUser.setDeptId(sysDept.getDeptId());
            sysUser.setUserName(sysDept.getPhone());
            sysUser.setNickName(sysDept.getDeptName());
            sysUser.setEmail(sysDept.getEmail());
            sysUser.setPhonenumber(sysDept.getPhone());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setType(1);
            sysUser.setUserId(sysUserMapper.selectUserMaxId() + 1L);
            sysUserMapper.insertUser(sysUser);
            //新增用户角色关联
            Long[] roleIds = new Long[1];
            roleIds[0] = 108L;
            if (StringUtils.isNotEmpty(roleIds)) {
                // 新增用户与角色管理
                List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
                for (Long roleId : roleIds) {
                    SysUserRole ur = new SysUserRole();
                    ur.setUserId(sysUser.getUserId());
                    ur.setRoleId(roleId);
                    list.add(ur);
                }
                sysUserRoleMapper.batchUserRole(list);
            }

        }

        return i;
    }

    /**
     * 批量删除部门
     *
     * @param ids 需要删除的部门主键
     * @return 结果
     */
    @Override
    public int deleteDeptApplyByIds(Long[] ids) {
        return deptApplyMapper.deleteDeptApplyByIds(ids);
    }

    /**
     * 删除部门信息
     *
     * @param id 部门主键
     * @return 结果
     */
    @Override
    public int deleteDeptApplyById(Long id) {
        return deptApplyMapper.deleteDeptApplyById(id);
    }
}
